package lockx

import (
	"fmt"
	"sync"

	"github.com/gookit/color"
)

//Mutex 互斥鎖
//RWMutex 讀寫鎖

// 並發場景 -->數據競爭

//var mp sync.Map //原子操作加锁，读多写少+ key值已经存在->修改

type CacheRwMutex struct {
	data         map[string]int
	sync.RWMutex // 多读 不互斥
}

func New() *CacheRwMutex {
	return &CacheRwMutex{
		data:    make(map[string]int),
		RWMutex: sync.RWMutex{},
	}

}

func (m *CacheRwMutex) Get(key string) int {
	m.RLock()
	defer m.RUnlock()
	value, ok := m.data[key]
	if ok {
		return value
	}
	return 0
}
func (m *CacheRwMutex) Set(key string, value int) {
	m.Lock()
	defer m.Unlock()
	m.data[key] = value

}
func RWSingle() {
	mutex := New()
	wg := sync.WaitGroup{}
	wg.Add(1)
	go func() {
		defer wg.Done()
		mutex.Set("a", 10)
	}()

	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			fmt.Println(mutex.Get("a"))

		}()

	}

	wg.Wait()
}
func RWSyncMap() {
	mp := sync.Map{}
	mp.Store("a", 1)
	mp.Store("b", 2)
	color.Greenln(mp.Load("a"))
	color.Greenln(mp.Load("b"))
	color.Yellowln(mp.LoadOrStore("ok", 11))
	color.Yellowln(mp.LoadOrStore("ok", 12))
	color.Cyanln(mp.LoadAndDelete("ok"))
	color.Cyanln(mp.LoadAndDelete("ok"))
	mp.Range(func(key, value any) bool { // 返回false则停止遍历
		fmt.Println(key, value)
		return true

	})
}
